package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.*;
import com.gable.exhibition.dao.FileDao;
import com.gable.exhibition.model.File;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.FileUploadService;
import com.gable.exhibition.util.CheckImportExcelHospital;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.ImportExcelHospitalModel;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lesson on 2018/2/24.
 */
@Controller
@RequestMapping(value="/fileUpload")
public class FileUploadController {

        Logger logger = Logger.getLogger(this.getClass());

        @Autowired
        FileUploadService fileUploadService;

/*
        @Value("${rootUrl}")
        String rootUrl;
*/
        @RequestMapping(value="/fileUpload",method = RequestMethod.POST, produces="application/json;charset=utf-8")
        @ResponseBody
        public ReturnResultUtil fileUpload(HttpServletRequest request, HttpServletResponse response){
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
            User user = CacheData.getSessionUser(null,1);

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            String rootPath = request.getSession().getServletContext().getRealPath(java.io.File.separator);

            if(StringUtil.isEmpty(multipartRequest.getParameter("keyId"))){
                return new ReturnResultUtil(500, MessageUtil.KEYIDISNULL);
            }

            if(StringUtil.isEmpty(multipartRequest.getParameter("keyType"))){
                return new ReturnResultUtil(500, MessageUtil.KEYTYPEISNULL);
            }

            String fileType = null;
            if(!StringUtil.isEmpty(multipartRequest.getParameter("fileType"))){
                fileType = multipartRequest.getParameter("fileType");
            }

            Long keyId = Long.parseLong(multipartRequest.getParameter("keyId"));
            String keyType = multipartRequest.getParameter("keyType");
            String fileDateStart =  multipartRequest.getParameter("fileDateStart");
            String fileDateEnd = multipartRequest.getParameter("fileDateEnd");
            String remark = multipartRequest.getParameter("remark");
            String type = multipartRequest.getParameter("type");
            List<File> fileList = new ArrayList<File>();

                Long ym = new Date().getTime();
                String filePath = "upload/" + ym;
                if (files != null && files.size() > 0) {
                    for (MultipartFile m : files) {
                        if(m.getBytes().length == 0){
                            return new ReturnResultUtil(500,MessageUtil.PLEASEUPLOADFILES);
                        }

                        String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".")+1);
                        String key = type+"/" + new Date().getTime()+"."+suffix;
                        boolean bl = FileUploadUtil.fileUpload(m.getBytes(), key);
                        if (!bl) {
                            return new ReturnResultUtil(500,MessageUtil.PLEASEUPLOADFILES);
                        }

                        key = FileUploadUtil.REALMNAME+"/"+key;

                        File file = new File();
                        file.setIsDel(0);
                        file.setCreatePerson(user.getUserId());
                        file.setCreateTime(df.format(new Date()));
                        file.setEndDate(fileDateEnd);
                        file.setStartDate(fileDateStart);
                        file.setFileName(m.getOriginalFilename());
                        file.setFileId(UUIDGenerator.getUniqueLong());
                        file.setFileSize(m.getSize());
                        file.setFileSuffix(suffix);
                        file.setFileType(fileType);
                        file.setKeyId(keyId);
                        file.setKeyType(Long.parseLong(keyType));
                        file.setFileUrl(key);
                        fileList.add(file);
                    }
                } else {
                    return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
                }
                return  fileUploadService.saveFileUpload(fileList);

            }catch (Exception e){
                    e.printStackTrace();
            }
            return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
        }

    @RequestMapping(value="/fileUploadForWeChat",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil fileUploadForWeChat(HttpServletRequest request, HttpServletResponse response){
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("files");
            String rootPath = request.getSession().getServletContext().getRealPath(java.io.File.separator);


            Long  userId = null;
            if( !StringUtil.isEmpty(multipartRequest.getParameter("userId"))){
                userId = Long.parseLong(multipartRequest.getParameter("userId"));
            }
//            User user = CacheData.getSessionUser(userId,1);
//            if(user == null)
//                return new ReturnResultUtil(500,MessageUtil.SESSIONNOTEXITIS);
            if(StringUtil.isEmpty(multipartRequest.getParameter("keyType"))){
                return new ReturnResultUtil(500, MessageUtil.KEYTYPEISNULL);
            }

            String fileType = null;
            if(!StringUtil.isEmpty(multipartRequest.getParameter("fileType"))){
                fileType = multipartRequest.getParameter("fileType");
            }

            String keyType = multipartRequest.getParameter("keyType");
            String fileDateStart =  multipartRequest.getParameter("fileDateStart");
            String fileDateEnd = multipartRequest.getParameter("fileDateEnd");
            String remark = multipartRequest.getParameter("remark");
            String type = multipartRequest.getParameter("type");
            List<File> fileList = new ArrayList<File>();

            Long ym = new Date().getTime();
            String filePath = "upload/" + ym;
            if (files != null && files.size() > 0) {
                for (MultipartFile m : files) {
                    if(m.getBytes().length == 0){
                        return new ReturnResultUtil(500,MessageUtil.PLEASEUPLOADFILES);
                    }

                    String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".")+1);
                    String key = type+"/" + new Date().getTime()+"."+suffix;
                    boolean bl = FileUploadUtil.fileUpload(m.getBytes(), key);
                    if (!bl) {
                        return new ReturnResultUtil(500,MessageUtil.PLEASEUPLOADFILES);
                    }

                    key = FileUploadUtil.REALMNAME+"/"+key;

                    File file = new File();
                    file.setIsDel(0);
                    file.setCreatePerson(userId);
                    file.setCreateTime(df.format(new Date()));
                    file.setEndDate(fileDateEnd);
                    file.setStartDate(fileDateStart);
                    file.setFileName(m.getOriginalFilename());
                    file.setFileId(UUIDGenerator.getUniqueLong());
                    file.setFileSize(m.getSize());
                    file.setFileSuffix(suffix);
                    file.setFileType(fileType);
                    file.setKeyType(Long.parseLong(keyType));
                    file.setFileUrl(key);
                    fileList.add(file);
                }
            } else {
                return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
            }
            return  fileUploadService.saveFileUpload(fileList);

        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }
}
